package com.lenovo.rc.sil.wangdwa.learning;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.lenovo.rc.sil.wangdwa.learning.service.EchoService;
import com.lenovo.rc.sil.wangdwa.learning.service.IEchoService;

public class ServiceDemoActivity extends Activity implements OnClickListener{
	
	
	private IEchoService mService = null;
	
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mService = IEchoService.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			mService = null;
		}
		
	};
	
	private Button btnBind = null;
	private Button btnUnbind = null;
	private Button btnTransaction = null;
	
	private EditText txtName  = null;
	

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnBind = (Button)findViewById(R.id.BTN_BIND);
        btnBind.setOnClickListener(this);
        btnTransaction = (Button)findViewById(R.id.BTN_TRANSACTION);
        btnTransaction.setOnClickListener(this);
        btnUnbind = (Button)findViewById(R.id.BTN_UNBIND);
        btnUnbind.setOnClickListener(this);
        
        txtName = (EditText)findViewById(R.id.TXT_NAME);
        
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.BTN_BIND:
			doBind();
			break;
		case R.id.BTN_TRANSACTION:
			doTransaction();
			break;
		case R.id.BTN_UNBIND:
			doUnbind();
			break;
		}
		
	}

	private void doUnbind() {
		// TODO Auto-generated method stub
		unbindService(mConnection);
		setButtons(false);
	}

	private void doTransaction() {
		// TODO Auto-generated method stub
		String echo = null;
		try {
			echo = mService.getEcho(txtName.getText().toString().trim());
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Toast.makeText(this, echo, Toast.LENGTH_LONG).show();
	}

	private void doBind() {
		// TODO Auto-generated method stub
		bindService(new Intent(EchoService.class.getName()), mConnection, Context.BIND_AUTO_CREATE);
		setButtons(true);
	}

	private void setButtons(boolean isActive) {
		// TODO Auto-generated method stub
		btnBind.setActivated(!isActive);
		btnUnbind.setActivated(isActive);
		
	}
}